﻿using System;
using System.Collections.Generic;

namespace JinYuan.VirtualDataLibrary
{
    public class DBSQL
    {

        /// <summary>
        /// 获取PLC换型参数绑定值
        /// </summary>
        /// <param name="modelName"></param>
        /// <returns></returns>
        public string GetPlcParamSql(string modelName)
        {
            string strSql = $@"SELECT '{modelName}' ModelName,pb.PLCAddress,pc.PLCValue,pc.UpdateTime,pb.PLCRemark,pb.OrderNum FROM Plcconfigbase pb 
                            left join (select * from Plcconfig where ModelName='{modelName}') pc on pb.PLCAddress = pc.PLCAddress order by pb.OrderNum";
            return strSql;
        }

        /// <summary>
        /// 获取产品型号参数
        /// </summary>
        /// <param name="strModelType"></param>
        /// <returns></returns>
        public string GetParamSql(string strModelType)
        {
            string strSql = $@"SELECT pb.ParaName, '{strModelType}' ModelName,pl.ParaValueMin,pl.ParaValueMax,pl.Uint,pb.Remark,pl.UpdateTime
                            FROM Parambase pb 
                            left join (select * from ParamList where ModelName = '{strModelType}' ) as  pl
                            on pb.ParaName = pl.ParaName order by pb.fNo asc";
            return strSql;
        }


        /// <summary>
        /// 获取产品型号列表
        /// </summary>
        /// <param name="strProdType"></param>
        /// <returns></returns>
        public string GetProdTypeSql(string strProdType = "")
        {
            string strSql = @"SELECT * FROM ProductModel ";
            if (strProdType != "")
            {
                strSql += string.Format(" where  ModelName='{0}'", strProdType);
            }
            strSql += "  order by  ModelName";
            return strSql;
        }


        /// <summary>
        /// 获取产品型号
        /// </summary>
        /// <param name="strModelType"></param>
        /// <returns></returns>
        public string GetProductParaByProdModel(string strModelType)
        {
            string strSql = $@"SELECT pb.ParaName, '{strModelType}' ModelName,pl.ParaValueMin,pl.ParaValueMax,pl.Uint,pb.Remark,pl.UpdateTime
                            FROM Parambase pb 
                            left join (select * from Paramlist where ModelName = '{strModelType}' ) as  pl
                            on pb.ParaName = pl.ParaName order by pb.fNo asc";
            return strSql;
        }


        public string GetPLCConfigBases()
        {
            string strSql = string.Format(@"SELECT * FROM Plcconfigbase ORDER BY OrderNum");
            return strSql;
        }


        public string GetSysAdminSql()
        {
            string strSql = string.Format(@"SELECT [LoginId]
                                                  ,[LoginName]
                                                  ,[LoginPwd]
                                                  ,[LoginUid]
                                                  ,[LoginLevel]
                                                  ,[SystemLog]
                                                  ,[CpkData]
                                                  ,[HistoryData]
                                                  ,[ParamSet]
                                                  ,[SystemSet]
                                                  ,[UserManage]
                                              FROM [dbo].[SysAdmin]");
            return strSql;
        }
        /// <summary>
        /// 获取RFID对应的B包参数
        /// </summary>
        /// <param name="strRFID"></param>
        /// <returns></returns>
        public string GetBGearEntity(string strRFID)
        {
            string strSql = $@"SELECT  `ChannelNo`,`BarCode`,`RFID`,`TestTime`,`CSBYHASCANNINGTIME`,`UpState`,`MaterialCode`  FROM `BGearEntity`  WHERE `RFID` = '{strRFID}'";

            return strSql;
        }
        public string GetBGearEntityByBarcode(List<string> listBarCode)
        {
            string strSql = $@"SELECT  *  FROM BGearEntity  WHERE BarCode in ('{string.Join("','", listBarCode)}')";

            return strSql;
        }
        /// <summary>
        /// 查询历史数据
        /// </summary>
        /// <param name="strBarCode"></param>
        /// <param name="strDate1"></param>
        /// <param name="strDate2"></param>
        /// <returns></returns>
        public string SelectHostData(int type, string strBarCode, string strDate1, string strDate2)
        {
            string strSql = "";
            try
            {
                if (type == 0)
                {
                    strSql = @"SELECT CONVERT(varchar,[TestTime], 120) 时间 
                                  ,[BarCode] 电芯码
                                  ,[Result] 结果
                                  ,[Remark] 备注
                                  ,case when [Flag]=1 then '已上传' else '未上传' end 上传状态
                              FROM [dbo].[AGearEntity] where TestTime >= '" + strDate1 + "' and TestTime <= '" + strDate2 + "' ";
                    if (strBarCode != "")
                    {
                        strSql += " and BarCode like '%" + strBarCode + "' ";
                    }
                }
                else if (type == 1)
                {
                    strSql = @"SELECT CONVERT(varchar,[CSBYHASCANNINGTIME], 120) 时间 
                        ,[CSBYHPROCESSNAME] 工序名
                        ,[CSBYHSCHEDULE] 班次
                        ,[CSBYHCODEA] 电芯码
                        ,[CSBYHOUTSTATIONJUDGMENTRESULT] 出站判定结果
                        ,[Remark] 备注
                        ,[RethrowNum] 复投次数
                        ,[CCDResult1] 电芯CCD1结果 
                        ,[CCDResult2] 电芯CCD2结果 
                        ,[CCDResult3] 电芯CCD3结果 
                        ,[CCDResult4] 电芯CCD4结果
                        ,[CCDResult5] 电芯CCD5结果 
                        ,[CCDResult6] 电芯CCD6结果
                        ,[CCDResult7] 电芯CCD7结果
                        ,[CCDResult8] 电芯CCD8结果
                        ,[CCDResult9] 电芯CCD9结果
                        ,[CCDResult10] 电芯CCD10结果
                        ,[CCDResult11] 电芯CCD11结果
                        ,[CCDResult12] 电芯CCD12结果
                        ,[CCDResult13] 电芯CCD13结果
                        ,[CCDResult14] 电芯CCD14结果
                        ,[CCDResult15] 电芯CCD15结果
                        ,[CCDResult16] 电芯CCD16结果
                        ,[CCDResult17] 电芯CCD17结果
                        ,[CCDResult18] 电芯CCD18结果 
                        ,[CCDResult19] 电芯CCD19结果 
                        ,[CCDResult20] 电芯CCD20结果
                        ,[CCDResult21] 电芯CCD21结果 
                        ,[CCDResult22] 电芯CCD22结果
                        ,[CCDResult23] 电芯CCD23结果
                        ,[CCDResult24] 电芯CCD24结果
                        ,[CCDResult25] 电芯CCD25结果
                        ,[CCDResult26] 电芯CCD26结果
                        ,[CCDResult27] 电芯CCD27结果                     
                        ,[Result] 结果
                        ,case when [Flag]=1 then '已上传' else '未上传' end 上传状态
                   FROM [dbo].[BGearEntity] where CSBYHASCANNINGTIME >= '" + strDate1 + "' and CSBYHASCANNINGTIME <= '" + strDate2 + "' ";
                    if (strBarCode != "")
                    {
                        strSql += " and CSBYHCODEA like '%" + strBarCode + "' ";
                    }
                }
            }
            catch (Exception ex)
            {
                CommonMethods.AddLog(true, ex.Message);
            }

            return strSql;
        }

        /// <summary>
        /// 查询报警历史数据
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="alarmType"></param>
        /// <returns></returns>
        public string SelectHostAlarmData(string start, string end, string alarmType)
        {
            string strSql = "";
            if (alarmType == "全天")
            {
                strSql = @"SELECT 
                                   CONVERT(varchar,[AlarmTime], 120) 时间 
                                  ,[PLCAdress] 报警地址
                                  ,[AlarmContent] 报警信息
                                  ,[AlarmCount] 报警次数
                                   ,[Class] 班次
                              FROM [dbo].[AlarmCountEntry] where AlarmTime >= '" + start + "' and AlarmTime <= '" + end + "' ";

            }
            else if (alarmType == "白班")
            {
                strSql = @"SELECT 
                                   CONVERT(varchar,[AlarmTime], 120) 时间 
                                  ,[PLCAdress] 报警地址
                                  ,[AlarmContent] 报警信息
                                  ,[AlarmCount] 报警次数
                                   ,[Class] 班次
                              FROM [dbo].[AlarmCountEntry]  where AlarmTime >= '" + start + "' and AlarmTime <= '" + end + "' and Class='白班'";
            }
            else
            {
                strSql = @"SELECT 
                                   CONVERT(varchar,[AlarmTime], 120) 时间 
                                  ,[PLCAdress] 报警地址
                                  ,[AlarmContent] 报警信息
                                  ,[AlarmCount] 报警次数
                                   ,[Class] 班次
                              FROM [dbo].[AlarmCountEntry]  where AlarmTime >= '" + start + "' and AlarmTime <= '" + end + "'  and Class='夜班'";
            }
            return strSql;
        }

        /// <summary>
        /// 按日统计
        /// </summary>
        /// <param name="startDateTime"></param>
        /// <param name="endDateTime"></param>
        /// <returns></returns>
        public string GetStaticByDay(string startDateTime, string endDateTime)
        {
            string strSql = $@" SELECT CONVERT(varchar(13),TestTime,120) 时间, ProdIn 总数, ProdOut OK总数,Ppm PPM均值,
                                cast(ROUND(JiaDL*100,1)as nvarchar(10))+'%' 稼动率均值,
                                cast(case when ProdIn>0 then (ROUND(cast(isnull(ProdOut,0) as float)/cast(isnull(ProdIn,0) as float)*100,2)) else 0 end as nvarchar(10) )+'%' 优率
                                FROM Hourprod WHERE TestTime BETWEEN  '{startDateTime}' AND '{endDateTime}' GROUP BY TestTime,ProdOut,ProdIn,Ppm,JiaDL
                                UNION ALL
                                SELECT '合计' as '时间', ProdIn '总数', ProdOut 'OK总数',Ppm 'PPM均值' ,JiaDL '稼动率均值',优率 as '优率' FROM (SELECT FDate,sum(ProdIn) ProdIn, SUM(ProdOut) ProdOut,AVG(PPM) Ppm,
                                 cast(ROUND(AVG(JiaDL)*100,1) as nvarchar(10))+'%' JiaDL, 
                                cast(case when (sum(ProdIn))>0 then (ROUND(cast(isnull(sum(ProdOut),0) as float)/cast(isnull(sum(ProdIn),0) as float)*100,2)) else 0 end as nvarchar(10) )+'%' 优率  FROM Hourprod
                                WHERE TestTime BETWEEN   '{startDateTime}' AND '{endDateTime}' GROUP BY FDate) as t ";

            return strSql;
        }

        /// <summary>
        /// 按周查询
        /// </summary>
        /// <param name="startDateTime"></param>
        /// <param name="endDateTime"></param>
        /// <returns></returns>
        public string GetStaticByWeek(string startDateTime, string endDateTime)
        {
            string strSql = $@" SELECT convert(char(10), TestTime, 120) 月份, sum(ProdIn) 总数, sum(ProdOut) OK总数,AVG(Ppm) PPM均值,
                                cast(ROUND(JiaDL*100,1)as nvarchar(10))+'%' 稼动率均值,
                                cast(case when sum(ProdIn)>0 then (ROUND(cast(isnull(SUM(ProdOut),0) as float)/cast(isnull(sum(ProdIn),0) as float)*100,2)) else 0 end as nvarchar(10) )+'%' 优率
                                FROM Hourprod WHERE TestTime BETWEEN  '{startDateTime}' AND '{endDateTime}' GROUP BY convert(char(10), TestTime, 120),JiaDL
                                UNION ALL
                                SELECT '合计' as '月份', ProdIn '总数', ProdOut 'OK总数',Ppm 'PPM均值' ,JiaDL '稼动率均值',优率 as '优率' FROM (SELECT sum(ProdIn) ProdIn, SUM(ProdOut) ProdOut,AVG(Ppm) Ppm,
                                cast(ROUND(AVG(JiaDL)*100,1) as nvarchar(10))+'%' JiaDL, 
                                cast(case when (sum(ProdIn))>0 then (ROUND(cast(isnull(sum(ProdOut),0) as float)/cast(isnull(sum(ProdIn),0) as float)*100,2)) else 0 end as nvarchar(10))+'%' 优率  FROM Hourprod
                                WHERE TestTime BETWEEN '{startDateTime}' AND '{endDateTime}') as t ";
            return strSql;
        }


        /// <summary>
        /// 按月查询
        /// </summary>
        /// <param name="startDateTime"></param>
        /// <param name="endDateTime"></param>
        /// <returns></returns>
        public string GetStaticByMonth(string startDateTime, string endDateTime)
        {
            string strSql = $@" SELECT convert(char(7), TestTime, 120) 月份, sum(ProdIn) 总数, sum(ProdOut) OK总数,AVG(Ppm) PPM均值,
                                cast(ROUND(JiaDL*100,1)as nvarchar(10))+'%' 稼动率均值,
                                cast(case when sum(ProdIn)>0 then (ROUND(cast(isnull(SUM(ProdOut),0) as float)/cast(isnull(sum(ProdIn),0) as float)*100,2)) else 0 end as nvarchar(10) )+'%' 优率
                                FROM Hourprod WHERE TestTime BETWEEN  '{startDateTime}' AND '{endDateTime}' GROUP BY convert(char(7), TestTime, 120),JiaDL
                                UNION ALL
                                SELECT '合计' as '月份', ProdIn '总数', ProdOut 'OK总数',Ppm 'PPM均值' ,JiaDL '稼动率均值',优率 as '优率' FROM (SELECT sum(ProdIn) ProdIn, SUM(ProdOut) ProdOut,AVG(Ppm) Ppm,
                                cast(ROUND(AVG(JiaDL)*100,1) as nvarchar(10))+'%' JiaDL, 
                                cast(case when (sum(ProdIn))>0 then (ROUND(cast(isnull(sum(ProdOut),0) as float)/cast(isnull(sum(ProdIn),0) as float)*100,2)) else 0 end as nvarchar(10))+'%' 优率  FROM Hourprod
                                WHERE TestTime BETWEEN '{startDateTime}' AND '{endDateTime}') as t ";
            return strSql;
        }

        /// <summary>
        /// 按班次统计
        /// </summary>
        /// <param name="dateTime"></param>
        /// <param name="shift"></param>
        /// <param name="changeShiftTime"></param>
        /// <returns></returns>
        public string GetStaticByShift(DateTime dateTime, string shift, string changeShiftTime)
        {
            string sDateTime1 = string.Empty;
            string sDateTime2 = string.Empty;
            if (shift == "白班")
            {
                DateTime sTempDateTime = Convert.ToDateTime($"{dateTime.ToString("yyyy-MM-dd")} {changeShiftTime}");

                sDateTime1 = sTempDateTime.AddHours(-12).ToString("yyyy-MM-dd HH:mm:ss");
                sDateTime2 = sTempDateTime.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {

                sDateTime1 = $"{dateTime.ToString("yyyy-MM-dd")} {changeShiftTime}";
                sDateTime2 = Convert.ToDateTime(sDateTime1).AddHours(12).ToString("yyyy-MM-dd HH:mm:ss");
            }

            string strsql = $@" SELECT CONVERT(varchar(13),TestTime,120) 时间, ProdIn 总数, ProdOut OK总数,Ppm PPM均值,
                                cast(ROUND(JiaDL*100,1)as nvarchar(10))+'%' 稼动率均值,
                                cast(case when ProdIn>0 then (ROUND(cast(isnull(ProdOut,0) as float)/cast(isnull(ProdIn,0) as float)*100,2)) else 0 end as nvarchar(10) )+'%' 优率
                                FROM Hourprod WHERE TestTime BETWEEN  '{sDateTime1}' AND '{sDateTime2}' GROUP BY TestTime,ProdOut,ProdIn,Ppm,JiaDL
                                UNION ALL
                                SELECT '合计' as '时间', ProdIn '总数', ProdOut 'OK总数',Ppm 'PPM均值' ,JiaDL '稼动率均值',优率 as '优率' FROM (SELECT FDate,sum(ProdIn) ProdIn, SUM(ProdOut) ProdOut,AVG(Ppm) Ppm,
                                cast(ROUND(AVG(JiaDL)*100,1) as nvarchar(10))+'%' JiaDL, 
                                cast(case when (sum(ProdIn))>0 then (ROUND(cast(isnull(sum(ProdOut),0) as float)/cast(isnull(sum(ProdIn),0) as float)*100,2)) else 0 end as nvarchar(10) )+'%' 优率  FROM Hourprod
                                WHERE TestTime BETWEEN  '{sDateTime1}' AND '{sDateTime2}' GROUP BY FDate) as t ";
            return strsql;
        }


        /// <summary>
        /// 获取最新的数据
        /// </summary>
        /// <returns></returns>
        public string GetStatic(string strDateTime)
        {

            string strsql = $@" SELECT [FDate]
                                      ,[FHour]
                                      ,[ProdIn]
                                      ,[ProdOut]                                     
                                      ,[TestTime]
                                  FROM [dbo].[Hourprod] where FDate='{strDateTime}' order by TestTime desc";
            return strsql;
        }

        /// <summary>
        /// 获取进站信息
        /// </summary>
        /// <returns></returns>
        public string GetInTime(string strBarCode)
        {
            string strSql = $@"SELECT [TestTime] 
                          ,[BarCode] 
                          ,[Result] 
                          ,[Remark] 
                            FROM [dbo].[AGearEntity] 
                            WHERE BarCode = '{strBarCode}'
                            ORDER BY TestTime ASC";

            return strSql;
        }

        /// <summary>
        /// 获取挑战件条码列表
        /// </summary>
        /// <param name="strProdType"></param>
        /// <returns></returns>
        public string GetChallengeCode(string strProdType = "")
        {
            string strSql = @"SELECT * FROM Challenge ";
            if (strProdType != "")
            {
                strSql += string.Format(" where  ChallengeBarCode='{0}'", strProdType);
            }
            strSql += "  order by  ChallengeBarCode";
            return strSql;
        }

    }
}
